package cn.dakaqi.services.user.impl;

import cn.dakaqi.dao.user.VolunteerMoneyDao;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.entities.user.VolunteerMoney;
import cn.dakaqi.services.user.VolunteerMoneyService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.util.Map;

/**
 * Created by chunyang on 2016/5/4.
 */
@Component(value = "volunteerMoneyService")
@Transactional
public class VolunteerMoneyServiceImpl implements VolunteerMoneyService
{
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    VolunteerMoneyDao volunteerMoneyDao;

    @Override
    public void create(String data) throws ServiceRuntimeException
    {
        VolunteerMoney volunteerMoney = new VolunteerMoney();
        save(volunteerMoney);
    }

    @Override
    public void save(VolunteerMoney volunteerMoney) throws ServiceRuntimeException
    {
        this.volunteerMoneyDao.save(volunteerMoney);
    }

    @Override
    public Page<VolunteerMoney> findByMemberCode(String memberCode, int type,int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("volunteer.memberCode", new SearchFilter("volunteer.memberCode", SearchFilter.Operator.EQ, memberCode));

        Specification<VolunteerMoney> spec = DynamicSpecifications.bySearchFilter(filters.values(), VolunteerMoney.class);
        return this.volunteerMoneyDao.findAll(spec, pageRequest);
    }

    @Override
    public Long findByMemberCode(String memberCode) throws ServiceRuntimeException
    {
        Volunteer volunteer = volunteerService.findByMemberCode(memberCode);
        if(null == volunteer)
            return 0L;
        return volunteerMoneyDao.findByMemberCode(volunteer.getId());
    }
}
